from django.shortcuts import render
from django.http import HttpResponse
# 导入 User 模型
from .models import User

def helloDjango(request):
  return HttpResponse('Hello Django.')

def add_user(request):
  if request.method=="POST":
    username = request.POST.get("username")
    password = request.POST.get("password")
    # 初始化一个user模型的ORM对象
    user = User()
    # 使用这个ORM来创建一条user记录，框架会自己去执行一条SQL插入语句，向数据库中插入一条数据
    user.username = username
    user.password = password
    # 将这个数据保存，类似于确定写入到数据库
    user.save()
    return HttpResponse("新增成功")
  else:
    return HttpResponse("不支持的请求!")

# 导入view视图类
from django.views import View
 
class UserListView(View):
  def get(self, request):
    # ORM方法 查出user表中的所有数据
    users = User.objects.all()
    re_list = []
    for item in users:
      re_dict = {}
      re_dict['username'] = item.username
      re_dict['gender'] = item.gender
      re_dict['phone'] = item.phone
      re_dict['email'] = item.email
      re_list.append(re_dict)
    return HttpResponse(str(re_list))


class UserView(View):
  def get(self, request):
    print(request)
    re_data = {'msg':'返回用户列表'}
    return HttpResponse(str(re_data))
  def post(self, request):
    re_data = {'msg':'新增用户'}
    return HttpResponse(str(re_data))
  def patch(self, request):
    re_data = {'msg':'局部修改用户'}
    return HttpResponse(str(re_data))
  def put(self, request):
    re_data = {'msg':'全部更新用户'}
    return HttpResponse(str(re_data))
  def delete(self, request):
    re_data = {'msg':'删除用户'}
    return HttpResponse(str(re_data))

from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import ModelViewSet
from .serializers import UserSerializer
class UserViewset(ModelViewSet):
    '''
    修改局部数据
    create:  创建用户
    retrieve:  检索某个用户
    update:  更新用户
    destroy:  删除用户
    list:  获取用户列表
    '''
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # drf 过滤&搜索&排序
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    # 搜索
    search_fields = ('username', 'phone', 'email',)
    # 过滤
    filter_fields = ('gender',)
    # 排序
    ordering_fields = ('updated', 'sort_time', 'created',)